from sanic.views import HTTPMethodView
from sanic.response import text,json
import urllib3
import json as jn
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format


class xiaOrder(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        html_data = request.json
        client_ip = request.ip
        user_id = request.app.ctx.user_id
        openid = ''
        phone = ''
        businessId = ''
        try:
            # 查询用户
            print(html_data)
            user_sql = f"select openid from c_users where openid='{html_data['wechat_openid']}' and phone='{html_data['wechatphone']}'"
            if db.find_one(user_sql):
                openid = html_data['wechat_openid']
                phone = html_data['wechatphone']
            else:
                return json({'code': 201, 'message': "用户不存在！"})
            # 查询商品
            goods_sql = f"select businessId from goods where id={int(html_data['id'])}"
            if db.find_one(goods_sql):
                print(eval(db.find_one(goods_sql)[0]))
                # # 查询商品归属店铺
                if html_data['businessId']:
                    if eval(db.find_one(goods_sql)[0])['businessId'] == html_data['businessId']:
                        businessId = html_data['businessId']
                else:
                    # 未设置店铺
                    pass

                #     1.微信支付
                if html_data['paypal_type'] == '1':
                    return json({'code': 201, 'message': "未开通微信支付！"})
                #     2.支付宝支付
                elif html_data['paypal_type'] == '2':
                    return json({'code': 201, 'message': "未开通支付宝支付！"})
                #     3.余额支付
                elif html_data['paypal_type'] == '3':
                    #     查询余额
                    rechargerecord_sql = f"select residue,id from rechargerecord where phone='{html_data['wechatphone']}' and status='1' and residue>0"
                    balance = [i for i in db.find_all(rechargerecord_sql)]
                    """
                        支付逻辑
                            1.先提取商品规格价格*数量
                    """
                    # 获取商品规格
                    balance_total1 = 0
                    balance_total = [i[0] + balance_total1 for i in db.find_all(rechargerecord_sql)]

                    goods_price = float(html_data['goodsSkuJson']['skuPrice']) * int(
                        html_data['goodsSkuJson']['quantity'])
                    if sum(balance_total) < goods_price:
                        return json({'code': 202, 'message': "余额不足！"})
                    for b in balance:
                        b_result = b[0] - goods_price
                        if b_result <= 0:
                            # 扣除余额
                            balance_sql_update = f"update rechargerecord set residue=0,status='4'  where id={b[1]}"
                            db.update(balance_sql_update)
                            continue
                        else:
                            # 如果第一份充值余额不够扣除第二份
                            balance_sql_update = f"update rechargerecord set residue={b_result}  where id={b[1]}"
                            db.update(balance_sql_update)
                            break
                        # 生成订单
                    order_id = Random_id(32, 'ORDER')
                    print(order_id)
                    order_create_sql = f"""insert into goods_order(merchant_id,order_id,business_id,wechat_openid
                                           ,wechatphone,goods_id,goods_sku,order_type,paypal_type,total_money,goods_money,status,ctime,utime
                                           ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),now())"""

                    db.insert(order_create_sql, (
                    user_id, order_id, businessId, openid, phone, html_data['id'], jn.dumps(html_data['goodsSkuJson']),
                    html_data['order_type'], html_data['paypal_type'], float(goods_price), float(goods_price), '支付成功'
                    ))
                    return json({'code': 200, 'message': "支付成功！"})
                #     4.月卡支付
                elif html_data['paypal_type'] == '4':
                    return json({'code': 201, 'message': "未开通月卡支付！"})
            else:
                return json({'code': 201, 'message': "商品不存在！"})

            return json({'code': 200, 'message': "请求成功！"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/order/createOrder', error))
            if openid:
                return json({'code': 500, 'message': "后端代码出错！"})
            else:
                return json({'code': 500, 'message': "appid或serct不对！"})